// pages/todos/todos.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    search: '',
    todos: [{
      name: 'Learning WEAPP',
      completed: false
    }, {
      name: 'Learning Javascript',
      completed: true
    }, {
      name: 'Learning HTML',
      completed: false
    }],
    leftCount: 2,
    allCompleted: false
  },
  inputChangeHandle: function (e) {
    this.setData({
      search: e.detail.value
    })
  },
  addToDoHandle: function () {
    if (!this.data.search) {
      return
    }
    var todos = this.data.todos;
    todos.push({
      name: this.data.search,
      completed: false
    })
    this.setData({
      todos: todos,
      search: '',
      leftCount: this.data.leftCount + 1
    })
  },
  toggleToDohandle: function (e) {
    var item = this.data.todos[e.currentTarget.dataset.index];
    item.completed = !item.completed;
    var leftCount = this.data.leftCount + (item.completed ? -1 : 1);
    this.setData({
      todos: this.data.todos,
      leftCount: leftCount
    })

  },
  removeTodoHandle(e) {
    var todos = this.data.todos;
    console.log(e.currentTarget.dataset.index);

    var item = todos.splice(e.currentTarget.dataset.index, 1)[0];
    var leftCount=this.data.leftCount-(item.completed?0:1);
    this.setData({
      todos: todos,
      leftCount:leftCount
    })
  },
  toggleAllHandle() {
    this.data.allCompleted = !this.data.allCompleted;
    var todos = this.data.todos;
    var that = this;
    todos.forEach(item => {
      item.completed = that.data.allCompleted
    });
    var leftCount=this.data.allCompleted?0:this.data.todos.length;
    this.setData({
      todos: todos,
      leftCount:leftCount
    })
  },
  clearHandle: function () {
    // var todos=[];
    // this.data.todos.forEach(item=>{
    //   if(!item.completed){
    //     todos.push(item);
    //   }
    // })
    var todos = this.data.todos.filter(item => {
      return !item.completed
    })
    this.setData({
      todos: todos
    })
  }
})